package com.github.boluo1230.wechat.base.config;

import com.github.boluo1230.wechat.util.ObjectUtil;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * @author Code Farmer
 * @date 2019/10/25 10:17
 */
@Component
public class MongoUtil {

    @Autowired
    private MongoTemplate mongoTemplate;

    public <T> int upsertOne(T object, Query query, Class<T> entityClass) {
        Update update = new Update();
        HashMap<String, Object> map = ObjectUtil.beanToMap(object);
        map.forEach(update::set);
        UpdateResult updateResult = mongoTemplate.upsert(query, update, entityClass);
        return updateResult.getModifiedCount() == 0 && updateResult.getUpsertedId() == null ? 0 : 1;
    }

}
